package com.farm.wcp.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.DropMode;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.farm.authority.domain.Organization;
import com.farm.authority.domain.Post;
import com.farm.authority.domain.User;
import com.farm.authority.service.OrganizationServiceInter;
import com.farm.authority.service.UserServiceInter;
import com.farm.core.page.ViewMode;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.file.FarmFileServiceInter;
import com.farm.file.domain.FileBase;
import com.farm.file.domain.FileResource;
import com.farm.file.domain.Visit;
import com.farm.file.domain.Visitlogs;
import com.farm.file.domain.ex.FileView;
import com.farm.file.enums.FileModel;
import com.farm.file.service.FileResourceServiceInter;
import com.farm.file.service.VisitServiceInter;
import com.farm.file.service.VisitServiceInter.OpModel;
import com.farm.file.service.VisitlogsServiceInter;
import com.farm.file.util.FarmImgs;
import com.farm.file.util.domain.ColorBean;
import com.farm.material.domain.Categray;
import com.farm.material.domain.Categrayfile;
import com.farm.material.domain.Tag;
import com.farm.material.domain.ex.JsTreeNode;
import com.farm.material.service.CategrayServiceInter;
import com.farm.material.service.CategrayfileServiceInter;
import com.farm.material.service.TagServiceInter;
import com.farm.wcp.util.CheckCodeUtil;
import com.farm.wcp.util.ThemesUtil;
import com.farm.wcp.util.ZxingTowDCode;
import com.farm.web.WebUtils;
import com.farm.web.easyui.EasyUiUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;


@RequestMapping("/ui")
@Controller
public class UIWebController extends WebUtils {
	private static final Logger log = Logger.getLogger(UIWebController.class);
	@Resource
	private UserServiceInter userServiceImpl;
	@Resource
	private OrganizationServiceInter organizationServiceImpl;
	@Resource
	private FarmFileServiceInter farmFileServiceImpl;
	@Resource
	private CategrayServiceInter categrayServiceImpl;
	@Resource
	private TagServiceInter tagServiceImpl;
	@Resource
	private FileResourceServiceInter fileResourceServiceImpl;
	@Resource
	private CategrayfileServiceInter categrayFileServiceImpl;
	@Resource
	private VisitlogsServiceInter visitLogsServiceImpl;
	@Resource
	private VisitServiceInter visitServiceImpl;

	@RequestMapping("/categrays")
	@ResponseBody
	public List<JsTreeNode> queryall(String name, HttpServletRequest request, HttpSession session) {
		List<JsTreeNode> list = new ArrayList<JsTreeNode>();
		list = categrayServiceImpl.getAllCategrays(name, getCurrentUser(session));
		return list;
	}

	
	@RequestMapping("/infoCategray")
	public ModelAndView infoCategray(String id, HttpSession session, HttpServletRequest request) {
		ViewMode view = ViewMode.getInstance();
		// 查询分类标签
		List<Tag> tags = tagServiceImpl.getTags(id);
		Categray categray = categrayServiceImpl.getCategrayEntity(id);
		List<FileResource> resources = fileResourceServiceImpl.getResources(true);
		if (categray != null) {
			Visitlogs vlog=	visitServiceImpl.getRecordLog(id, OpModel.BOOK, getCurrentUser(session));
			if(vlog!=null) {
				view.putAttr("vlogid", vlog.getId());
			}
			// Visit visit = visitServiceImpl.record(id, OpModel.VISIT,
			// getCurrentUser(session));
			Visitlogs praise = visitServiceImpl.getRecordLog(id, OpModel.PRAISE, getCurrentUser(session));
			List<Visitlogs> comments = visitServiceImpl.getRecordLogs(id, OpModel.COMMENTS);
			view.putAttr("comments", comments);
			view.putAttr("praise", praise);
			view.putAttr("visit", visitServiceImpl.getVisitByAppId(id));
		}else {
			if (id.equals(OpModel.BOOK.name())) {
				// 订阅
				view.putAttr("title", "我的分类订阅");
			}
			if (id.equals(OpModel.FAVORITES.name())) {
				// 收藏
				view.putAttr("title", "我的文件收藏");
			}
			if (id.equals(OpModel.VISIT.name())) {
				// 最近訪問
				view.putAttr("title", "我的最近访问文件");
			}
			if (id.equals("RECYCLE")) {
				// 回收站
				view.putAttr("title", "我的回收站");
			}
		}
		return view.putAttr("categray", categray).putAttr("id", id).putAttr("tags", tags)
				.putAttr("resources", resources).returnModelAndView("web-pc/infos/pc-info-categray");
	}

	
	@RequestMapping("/infoFile")
	public ModelAndView infoFile(String appId, HttpSession session, HttpServletRequest request) {
		ViewMode view = ViewMode.getInstance();
		String fileid = null;
		for (OpModel om : OpModel.values()) {
			if (appId.indexOf(om.name()) == 0) {
				// 收藏夹来源的
				String vlogid = appId.replace(om.name(), "");
				Visitlogs vlog = visitLogsServiceImpl.getVisitlogsEntity(vlogid);
				fileid = vlog.getAppid();
				view.putAttr("visitmode", om.name());
				view.putAttr("vlogid", vlogid);
			}
		}
		if (fileid == null) {
			// 來自分類
			Categrayfile cf = categrayFileServiceImpl.getCategrayfileEntity(appId);
			{
				Categray categray = categrayServiceImpl.getCategrayEntity(cf.getCategrayid());
				List<Tag> tags = tagServiceImpl.getTags(categray.getId());
				view.putAttr("categray", categray).putAttr("tags", tags).putAttr("categrayFileId", appId);
			}
			fileid = cf.getFileid();
			view.putAttr("pstate", cf.getPstate());
			visitServiceImpl.record(fileid, OpModel.VISIT, getCurrentUser(session));
		}
		view.putAttr("visit", visitServiceImpl.getVisitByAppId(fileid));
		Visitlogs praise = visitServiceImpl.getRecordLog(fileid, OpModel.PRAISE, getCurrentUser(session));
		List<Visitlogs> comments = visitServiceImpl.getRecordLogs(fileid, OpModel.COMMENTS);
		view.putAttr("comments", comments);
		view.putAttr("praise", praise);

		FileView file = null;
		try {
			file = farmFileServiceImpl.getFileInfo(fileid);
		} catch (FileNotFoundException e) {
			view.putAttr("msg", e.getMessage());
		}
		FileModel model = FileModel.getModelByFileExName(file.getFile().getExname());
		if (model.equals(FileModel.IMG)) {
			view.putAttr("img", file);
			try {
				List<ColorBean> colors = FarmImgs.getColors(farmFileServiceImpl.getPersistFile(fileid).getFile(), 7);
				view.putAttr("colors", colors);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return view.putAttr("model", model.name()).putAttr("file", file)
				.returnModelAndView("web-pc/infos/pc-info-file");
	}

	
	@RequestMapping("/categrayfiles")
	public ModelAndView categrayfiles(String word, String colum, String layout, String sort, String categrayid,
			Integer page, HttpSession session, HttpServletRequest request) {
		ViewMode view = ViewMode.getInstance();
		view.putAttr("categrayKey", categrayid);
		List<FileView> files = new ArrayList<FileView>();
		List<FileView> dirs = new ArrayList<FileView>();
		Categray categray = categrayServiceImpl.getCategrayEntity(categrayid);
		if (categray != null) {
			view.putAttr("categray", categray);
			if (!categray.getParentid().equals("NONE")) {
				view.putAttr("parentId", categray.getParentid());
			}
		}
		files = categrayServiceImpl.getFiles(categrayid, page);
		dirs = categrayServiceImpl.getCategrays(categrayid);
		if (categrayid.equals(OpModel.BOOK.name())) {
			// 订阅
			dirs = categrayServiceImpl.getVlogCategrays(getCurrentUser(session), OpModel.BOOK, 1);
		}
		if (categrayid.equals(OpModel.FAVORITES.name())) {
			// 收藏
			files = categrayServiceImpl.getVlogFiles(getCurrentUser(session), OpModel.FAVORITES, 1);
		}
		if (categrayid.equals(OpModel.VISIT.name())) {
			// 最近訪問
			files = categrayServiceImpl.getVlogFiles(getCurrentUser(session), OpModel.VISIT, 1);
		}
		if (categrayid.equals("RECYCLE")) {
			// 回收站
			files = categrayServiceImpl.getRecycleFiles(getCurrentUser(session),1);
		}
		if (StringUtils.isNotBlank(word)) {
			files = files.stream().filter(o -> o.getTitle().indexOf(word) >= 0).collect(Collectors.toList());
		}
		if (StringUtils.isNotBlank(word)) {
			dirs = dirs.stream().filter(o -> o.getTitle().indexOf(word) >= 0).collect(Collectors.toList());
		}
		if (sort != null && !sort.toUpperCase().equals("NONE")) {
			if (sort.equals("time")) {
				Collections.sort(files, (o1, o2) -> o2.getCtime().compareTo(o1.getCtime()));
			}
			if (sort.equals("title")) {
				Collections.sort(files, (o1, o2) -> o1.getTitle().compareTo(o2.getTitle()));
			}
			if (sort.equals("size")) {
				Collections.sort(files, (o1, o2) -> o2.getLen() - o1.getLen());
			}
			if (sort.equals("ex")) {
				Collections.sort(files, (o1, o2) -> o2.getExname().compareTo(o1.getExname()));
			}
		}

		int col_num = 3;
		if (colum != null && !colum.toUpperCase().equals("NONE")) {
			if (colum.equals("1")) {
				col_num = 12;
			}
			if (colum.equals("2")) {
				col_num = 6;
			}
			if (colum.equals("4")) {
				col_num = 3;
			}
			if (colum.equals("6")) {
				col_num = 2;
			}
		}

		view.putAttr("col_num", col_num).putAttr("files", files).putAttr("dirs", dirs);
		if (layout != null && !layout.toUpperCase().equals("NONE")) {
			if (layout.equals("grid")) {
				// 默认
			}
			if (layout.equals("list")) {
				return view.returnModelAndView("web-pc/infos/pc-categray-files-list");
			}
		}
		return view.returnModelAndView("web-pc/infos/pc-categray-files-grid");

	}
}
